/*###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.9
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############*/


JFX_AdminTabber = function(blocker){
    if(false === (blocker instanceof Object)){
        return;
    }
    var tabberEl = $('#jfx-toolbar .tab-holder').get(0);
    if(!tabberEl){
        alert('No tab holder found');
        return;
    }
    this.tabData = Array();
    this.tabs = Array();
    this.tabberEl = tabberEl;
    this.focussedTab = null;
    this.blocker = blocker;
    var tabUl = document.createElement('ul');
    this.addElements(blocker.page.elements, tabUl);

}

JFX_AdminTabber.prototype = new JFX_Base();


JFX_AdminTabber.prototype.addElements = function(els, container){

    for(var i=0; i<els.length; i++){
        var el = els[i];
        var elementId = el.id;
        var tabDataLength = this.tabData.length;
        this.tabData[tabDataLength] = el;

        // find out if this is a template or not
        var isTemplate = false;
        if(el.details.template_id.length > 0 && this.blocker.mode == 'page'){
            // yes, let's create a mirror to the original block
            isTemplate = true;
        }

        var tab = document.createElement('li');
        var link;
        if(!isTemplate) link = document.createElement('a');
        else link = document.createElement('span');
        var me = this;
        tab.className = 'tab';
        $(link).html(el.details.title);
        link.id = 'jfxblock-tab-'+el.id;
        $(tab).append(link);

        

		$(link).click(function(){
			var blockId = this.id.replace('jfxblock-tab-', '');
			AdminBlocks.tabber.focusTab(blockId);
			AdminBlocks.showMyActions(document.getElementById(blockId));
		});
        
        tab.id = 'jfx-tabber-'+el.id;
        this.tabs[this.tabs.length] = tab;
        if(el.elements && el.elements.length > 0){
            var newContainer = document.createElement('ul');
            tab.appendChild(newContainer);
            this.addElements(el.elements, newContainer);
        }
        container.appendChild(tab);
    }

}

JFX_AdminTabber.prototype.triggerButton = function(button){

	var tab, evalFunction;

	tab = button;

	if(!tab){
		if(button.blockId!=AdminBlocks.pageId){
			return;
		}
		tab = AdminBlocks.page;
	}
    this.focussedTab = tab;

    this.showToolbarButtons(button);

    AdminBlocks.tabber.loadButtonContent(button);

	if(button.rebuildPage){
		evalFunction = function(){
			AdminBlocks.rebuildPage();
		}
	}else{
		evalFunction = function(){}
	}

	$.getJSON(this.ajaxUrl+'/get-block-button-content/', tab, evalFunction);

}


JFX_AdminTabber.prototype.focusTab = function(button){
	
    this.focussedTab = button;

    this.showToolbarButtons(button);

    AdminBlocks.tabber.loadButtonContent(button);

}

JFX_AdminTabber.prototype.findBlock = function(blockId){
	return AdminBlocks.findElement(AdminBlocks.page.elements, blockId);
}
JFX_AdminTabber.prototype.getTabData = function(tabId){
    for(var i=0; i<this.tabs.length; i++){
        if(this.tabs[i].id == tabId) return this.tabData[i];
    }
    return false;
}

JFX_AdminTabber.prototype.showToolbarButtons = function(button){
    var evalFunction = function(json){
        $('#jfx-toolbar-buttons').html(json.content);
    }
    $.getJSON(this.ajaxUrl+'/get-block-buttons/', button, evalFunction);
}

JFX_AdminTabber.prototype.loadButtonContent = function(button){
	AdminBlocks.tabber.setValue('currentButtonModule', button.moduleName);
    AdminBlocks.tabber.setValue('currentButtonMethod', button.moduleMethod);
    AdminBlocks.tabber.setValue('currentButtonId', button.id);
	AdminBlocks.tabber.setValue('rebuildPage', button.rebuildPage);

    var evalFunction = function(json){
        $('#jfx-toolbar-content').html(json.content);
        $('#jfx-toolbar-messages').html(json.error+json.success);
        eval(json.js);
        $('#jfx-toolbar-content form').submit(function(){
            if($('input[type=file]', this).get().length > 0){
                // contains a file field, submit normally
                return true;
            }
            var ajaxSubmitOptions = {
                'success' : function(){alert('success!');},
                'error' : function(){alert('error!');},
                'dataType' : 'text',
                'contentType' : 'text/html'
            };

            if($('input[type=file]', this).get().length > 0){
                $(this).ajaxSubmit(ajaxSubmitOptions);
            }else{
                var evalFunction2 = function(json){
                    eval(evalFunction(json));
                }


                $.post(this.action, $(this).serialize(), evalFunction2, 'json');
                
            }
            return false;
        });

        AdminBlocks.tabber.makeAjaxLinks();
		
    }

    $.getJSON(this.ajaxUrl+'/get-block-button-content/', button, evalFunction);

	//
}

JFX_AdminTabber.prototype.makeAjaxLinks = function(){
    $('#jfx-toolbar-content a').each(function(){
        $(this).click(function(){
            if($(this.parentNode).hasClass('redirect')) return true;
            var href = $(this).attr('href');
            if(href.substring(0, 11) === 'javascript:' || href.substring(0, 1) === '#') return;
            JFXShowLoadingAnimation();
            $.getJSON(href, {'JFXGetAjaxContent' : '1'}, AdminBlocks.tabber.parseAjaxContent);
            return false
        });
    });

}








JFX_AdminTabber.prototype.parseAjaxContent = function(json){
    
    $('#jfx-toolbar-content').text(json._MAIN);
    JFXHideLoadingAnimation();
    eval(json._JS);

    $('#jfx-toolbar-content form').each(function(){
        var newAction = $(this).attr('action').replace('JFXGetAjaxContent=1', '');

        if(newAction.substring(newAction.length-1)==='?'){
            newAction = newAction.substr(0, newAction.length-1);
        }

        if($('input[type=file]', this).get().length > 0){
            // form contains a file field, we cannot ajaxify this one
            this.action = newAction
        }else{
            if(newAction.match('\\\?')){
                newAction += '&JFXGetAjaxContent=1';
            }else{
                newAction += '?JFXGetAjaxContent=1';
            }
            this.action = newAction;
        }
    });
    $('#jfx-workspace-inner form').submit(function(){
        if($('input[type=file]', this).get().length > 0){
            // contains a file field, submit normally
            return true;
        }
        var ajaxSubmitOptions = {
            'success' : JFXAjaxSubmitSuccess,
            'error' : JFXAjaxSubmitError,
            'dataType' : 'text',
            'contentType' : 'text/html'
        };

        if($('input[type=file]', this).get().length > 0){
            $(this).ajaxSubmit(ajaxSubmitOptions);
        }else{
            $.post(this.action, $(this).serialize(), JFXAjaxSubmitSuccess, 'text');
        }
        return false;
    });

    // make the page tree redirect the whole page instead of load ajax content
    $('#jfx-pages-menu a').each(function(){
        if(!$(this.parentNode).hasClass('redirect')) $(this.parentNode).addClass('redirect');
    });

    AdminBlocks.tabber.makeAjaxLinks();

}










